home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5169 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.9 KB  |  64 lines

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: External access to private class variables
  5. Date: 02 Feb 1996 19:34:23 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Feb2203423@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <4ermr9$ii7@cloner2.ix.netcom.com>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: genescot@ix.netcom.com's message of 2 Feb 1996 00:45:29 GMT
  12.  
  13. In article <4ermr9$ii7@cloner2.ix.netcom.com> genescot@ix.netcom.com(Eugene S. Thompson ) writes:
  14.  
  15.    I was playing around with references and ran across this situation. I'm
  16.    sure it's not original, so I was hoping someone could tell me if it is
  17.    an intentional implementation of C++ or if it is a bug.
  18.  
  19.    class X 
  20.    {
  21.    private:
  22.        int value;
  23.    public:
  24.        X (int n = 0) { value = n; }
  25.        int& GSValue () { return value; }   // return a reference to the 
  26.                        // private member "value"
  27.    };
  28.        .
  29.        .
  30.        .
  31.    main ()
  32.    {
  33.    X   x1 (20);
  34.  
  35.        printf ("%d\n", x1.GSValue ());     // 20
  36.  
  37.    int* pntr = &(x1.GSValue ());
  38.  
  39.        printf ("%d\n", *pntr);             // 20
  40.  
  41.        *pntr = 30;
  42.        printf ("%d\n", x1.GSValue ());     // 30 -> We now have external 
  43.                        // access to a private member.
  44.    }
  45.  
  46.    I realize that this implementation is contrived, but I'm sure there are
  47.    additional ways of gaining such access. So, what's the deal? 
  48.  
  49. It's even possible to modify the private member directly:
  50.  
  51. int main ()
  52. {
  53.    X x1 (20);
  54.    printf ("%d\n", x1.GSValue ());     // 20
  55.    x1.GSValue()=30;
  56.    printf ("%d\n", x1.GSValue ());     // 30
  57. }
  58.  
  59. You return a non-const reference and therefore it's perfectly valid to
  60. modify the referred variable. One should take care with services that
  61. provide uncontrolled access to private members.
  62.  
  63.         Enno
  64.